﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using CitiesWeather.Models;

namespace CitiesWeather.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //CityViewModel model = new CityViewModel();
            IList<CityViewModel> model = new List<CityViewModel>();

            try
            {
               


                XElement CitiesFile = XElement.Load(Server.MapPath("~/App_Data/Cities.xml"));
                var Cities = (from city in CitiesFile.Elements("City")
                              from name in city.Elements("Name")
                              select new {CityName = name.Value});


                WebClient webClient = new WebClient();

                foreach (var city in Cities)
                {
                    CityViewModel cityViewModel = new CityViewModel();
                    string response =
                        webClient.DownloadString(
                            "http://api.wunderground.com/api/YOURAPIKEY/conditions/forecast/q/" + city.CityName);
                    XElement xResponse = XElement.Parse(response);
                    XElement xCity = xResponse.Descendants("city").First();
                    cityViewModel.City = xCity.Value;
                    XElement temperatureElement = xResponse.Descendants("temp_f").First();
                    cityViewModel.Temperature = int.Parse(Math.Round(Decimal.Parse(temperatureElement.Value)).ToString());

                    XElement xHighElement = xResponse.Descendants("high").First().Element("fahrenheit");
                    cityViewModel.HighTemp = int.Parse(Math.Round(Decimal.Parse(xHighElement.Value)).ToString());
                    XElement xLowElement = xResponse.Descendants("low").First().Element("fahrenheit");
                    cityViewModel.LowTemp = int.Parse(Math.Round(Decimal.Parse(xLowElement.Value)).ToString());
                    XElement xIconURL = xResponse.Descendants("icon_url").First();
                    cityViewModel.icon_url = xIconURL.Value;
                    XElement xHumidity = xResponse.Descendants("avehumidity").First();
                    cityViewModel.Humidity = int.Parse(xHumidity.Value);
                    model.Add(cityViewModel);
                }
            }
            catch (Exception e)
            {
                ViewBag.Message = "An error occured. Please try again or report problem to webmaster.";
            }

            return View(model);
        }
    }
}